import {Icon, Input, Tree} from 'antd';
// import Icon from '../../../_antd1.11.2/icon'
// import Input from '../../../_antd1.11.2/input'
// import Tree from '../../../_antd1.11.2/tree'
const TreeNode = Tree.TreeNode;
import WeaTools from '../../wea-tools';
import isEmpty from 'lodash/isEmpty';
import isString from 'lodash/isString';
import isEqual from 'lodash/isEqual';
import isArray from 'lodash/isArray';
import forEach from 'lodash/forEach';
import uniq from 'lodash/uniq';

let that = new Object();
class Main extends React.Component {
    constructor(props) {
        super(props);
        const {defaultExpandedKeys,treeData} = props;
        this.state = {
            expandedKeys:defaultExpandedKeys,
            selectedKeys:[],
            treeData:treeData || [],
            defaultExpandedKeys:defaultExpandedKeys,
            checkedKeys: [],
            radioCheckedData: props.radioCheckedData || '',
            checkedDatas: [],
        }
        that = this;
    }
    componentDidMount() {
        const{treeData} = this.state;
        generateData(treeData);
        this.setState({
            treeData: objToArray(treeData),
        });
    }
    componentWillReceiveProps(nextProps) {
        const {componyParam} = this.props;
        if(componyParam && componyParam != nextProps.componyParam){//虚拟维度
            generateData(nextProps.treeData);
            this.setState({
                expandedKeys:nextProps.defaultExpandedKeys,
                treeData: objToArray(nextProps.treeData),
            });
        }
        if(!isEqual(this.props.treeData, nextProps.treeData)){//初始树数据
            generateData(nextProps.treeData);
            this.setState({
                treeData: objToArray(nextProps.treeData),
            });
        }
        if(!isEqual(this.props.defaultExpandedKeys, nextProps.defaultExpandedKeys)){//初始展开的树节点
            this.setState({
                defaultExpandedKeys:nextProps.defaultExpandedKeys,
                expandedKeys:nextProps.defaultExpandedKeys,
            });
            this.state.checkedKeys && this.state.checkedKeys.length > 0 && this.updateExpandedKeys(this.state.checkedKeys, nextProps.defaultExpandedKeys);
        }
        if ('radioCheckedData' in nextProps) {
            if(!isEqual(this.state.radioCheckedData, nextProps.radioCheckedData)){//单选数据受控
                this.setState({radioCheckedData: nextProps.radioCheckedData});
            }
        }
        if ('checkedDatas' in nextProps) {
            if(!isEqual(this.props.checkedDatas, nextProps.checkedDatas) || !isEqual(this.state.checkedDatas, nextProps.checkedDatas)){//多选数据受控
                let checkedKeys = this.formatCheckDatas(nextProps.checkedDatas)
                this.updateExpandedKeys(checkedKeys);
                this.setState({
                    checkedKeys,
                    checkedDatas: nextProps.checkedDatas
                });
            }
        }
    }
    formatCheckDatas(checkedDatas) {
        let keys = [];
        if (isArray(checkedDatas) && checkedDatas.length > 0) {
            forEach(this.treeDataList, (item, key)=> {
                if (checkedDatas.some((d) => d.id==item.id && d.name==item.name)) {
                    keys.push(key);
                }
            })
        }
        return keys;
    }
    updateExpandedKeys(checkedKeys, expandedKeys) {
        expandedKeys = expandedKeys || this.state.expandedKeys;
        if (isArray(checkedKeys) && checkedKeys.length > 0) {
            let parentIds = [];
            checkedKeys.forEach(k => parentIds.push(this.treeDataList[k].pid));
            forEach(this.treeDataList, (item, key)=> {
                if (parentIds.some((d) => d == item.id)) {
                    expandedKeys.push(key);
                }
            })
        }
        expandedKeys = uniq(expandedKeys);
        this.setState({expandedKeys});
    }
    onCheck(checkedKeys,e) {
        this.setState({
          checkedKeys
        });
        const {isMult} = this.props;
        if(isMult) {
            let selectNodes = [];
            let ids = [];
            checkedKeys.forEach((i)=> {
                if (this.treeDataList[i].canClick) {
                    let d = {};
                    d.id = this.treeDataList[i].id;
                    d.name = this.treeDataList[i].name;
                    selectNodes.push(d);
                    ids.push(this.treeDataList[i].id);
                }
            })
            this.props.checkedCb && this.props.checkedCb(ids, selectNodes);
        }
    }
    onSelect(keys, e) {
        const {isMult} = this.props;
        if(typeof this.props.onSelect=='function'){
            this.props.onSelect(e);
        }
        if(!isMult) {
            this.setTheDatas(keys, e.selectedNodes);
        }

    }
    onDoubleClick(key) {
        if (this.isCheckedDisable(this.treeDataList[key])) return;
        this.props.onDoubleClick && this.props.onDoubleClick([this.treeDataList[key]]);
    }
    setTheDatas(selectTreeKeys, nodes) {
        let idArr = [];
        let nameArr = [];
        let keys = [];
        for(let i = 0,length = nodes.length; i < length; i++) {
            const node = nodes[i].props;
            if(node.canClick){
                idArr.push(node.id);
                nameArr.push(node.name);
                keys.push(selectTreeKeys[i]);
            }
        }
        this.setState({
            selectedKeys:keys,
        });
        let ids = idArr.join(",");
        let names = nameArr.join(",");
        if(typeof this.props.setData === "function"){
            this.props.setData(ids,names);
        }
    }
    onLoadData(treeNode) {
        let  _this = this;
        const {dataUrl, keyword, params}=this.props;
        const browserType = this.props.type;
        const treeData = [...this.state.treeData];
        const {eventKey,treeKey,isVirtual,type,psubcompanyid,id} = treeNode.props;
        // let params = `&type=${type}&id=${id}&isVirtual=${isVirtual}`;//（当前节点是部门的需要传递psubcompanyid）
        // (this.props.type == 4) && (params += '&isLoadSubDepartment=1');//加载部门
        let innerParams = browserType == 4 ? {isLoadSubDepartment:1,type:type,id:id,isVirtual:isVirtual} : {type:type,id:id,isVirtual:isVirtual}
        if (keyword) innerParams.keyword = keyword;
        let searchParams = {...params, ...innerParams};
        return new Promise(resolve => {
            WeaTools.callApi(dataUrl,'GET',searchParams).then(datas => {
                // console.log("datas",datas);
                getNewTreeData(treeData, treeKey, generateTreeNodes(datas,treeNode), 2);
                // console.log("treeData:",treeData);
                _this.setState({treeData});
                resolve();
            });
        });
    }
    isCheckedDisable(item) {
        const {filterData,inputId,inputName} = this.props;
        if (!item.canClick) {
            return true;
        }
        if (!isEmpty(filterData)) {
            let id = inputId || 'id';
            let name = inputName || 'name';
            return filterData.some((d)=>item.id === d[id] && item.name === d[name]);
        }
        return false;
    }
    isRadioDisable(item) {
        return !item.canClick || false;
    }
    isRadioChecked(item) {
        let bool = false;
        const {radioCheckedData} = this.state;
        if (!isEmpty(radioCheckedData)) {
            if (isString(radioCheckedData)) {
                bool = item.treeKey == radioCheckedData;
            } else {
                bool = item.id == radioCheckedData.id;
            }
        }
        return bool;
    }
    onExpandChange(expandedKeys, nodeObj){
        this.setState({expandedKeys:expandedKeys})
    }
    onRadioCheck(key) {
        if (key) {
            this.setState({radioCheckedData: key});
            const data = this.treeDataList[key];
            this.props.setRadioData && this.props.setRadioData(data.id, data.name, data);
        }
    }
    render() {
        const {expandedKeys,ids,selectedKeys,checkedKeys} = this.state;
        const {isLoadUser,checkable,browserTree,isMult,hasRadio,checkStrictly = false, isLoadAll = false}=this.props;
        const loop = (data,level) => data.map(item => {
            let title = <div title={item.title || item.name}>{item.icon ? <i className={item.icon} style={{marginRight: '5px'}}/>:''}{item.name}</div>;
            if(isLoadUser && item.type == "3"){
                title = (
                    <div>
                        <img className="wea-tree-hr-portrait" src={item.icon} alt="portrait"/>
                        <span style={{paddingLeft:10}}>{item.name}</span>
                    </div>
                );
            }
            if (item.children) {
                for(let i =0;i<item.children.length;i++){
                    item.children[i].treeKey = `${item.treeKey}-${item.children[i].id}`;
                    // item.children[i].isParent ? (item.children[i].isLeaf = false) : (item.children[i].isLeaf = true);
                }
            }
            item.isLeaf = !item.isParent;
            this.treeDataList[item.treeKey] = item;
            return <TreeNode browserTree={browserTree} level={level}
                        isVirtual={item.isVirtual}
                        type={item.type}
                        title={title}
                        name={item.name}
                        key={item.treeKey}
                        id={item.id}
                        treeKey={item.treeKey}
                        isLeaf={item.isLeaf}
                        disableCheckbox={this.isCheckedDisable(item)}
                        disableRadio={this.isRadioDisable(item)}
                        radioChecked={this.isRadioChecked(item)}
                        expanded={true}
                        canClick={item.canClick}
                    >
                        {item.children && loop(item.children,level+1)}
                    </TreeNode>
        });
        this.treeDataList = {};
        const treeNodes = this.state.treeData.length && loop(this.state.treeData, 0);
        return (
            <Tree className="my-tree"
                defaultExpandedKeys={this.state.defaultExpandedKeys}
                expandedKeys={this.state.expandedKeys}
                onExpand={this.onExpandChange.bind(this)}
                onSelect={this.onSelect.bind(this)}
                onCheck={this.onCheck.bind(this)}
                loadData={isLoadAll? null: this.onLoadData.bind(this)}
                checkable={isMult}
                checkedKeys={checkedKeys}
                checkStrictly={checkStrictly}
                onRadioCheck={this.onRadioCheck.bind(this)}
                hasRadio={hasRadio}
                multiple={isMult}
                selectedKeys={selectedKeys}
                needExpandChildren
                clickNodeExpandChildren={this.props.clickNodeExpandChildren}
                onDoubleClick={this.onDoubleClick.bind(this)}
                >
                {treeNodes}
            </Tree>
        )
    }
};

function objToArray(obj) {
    if (!isArray(obj)) {
        let arr = [];
        arr.push(obj);
        obj = arr;
    }
    return obj;
}

function generateData(data, level = 1) {
    if (!isEmpty(data)) {
        const {topPrefix} = that.props;
        if (!isArray(data)) {
            data.isLeaf = !data.isParent;
            if (level == 1) data.treeKey = `${topPrefix}0-${data.id}`;
            data.children = data.subs || data.children;
            if (data.children && data.children.length > 0) generateData(data.children, level+1);
        } else {
            data.forEach((item) => {
                item.isLeaf = !item.isParent;
                if (level == 1) item.treeKey = `${topPrefix}0-${item.id}`;
                item.children = item.subs || data.children;
                if (item.children && item.children.length > 0) generateData(item.children, level+1);
            })
        }
    }
}

function generateTreeNodes(data,treeNode) {
    let datas = data;
    if(!data.length){
        datas = new Array(datas);
    }
    // console.log("datas",datas,'treeNode',treeNode);
    let arr = new Array();
    const {topPrefix} = that.props;
    if(!treeNode){
        for (let i=0;i<datas.length;i++) {
            const data = datas[i];
            data.treeKey = `${topPrefix}0-${data.id}`;
            data.isLeaf = !data.isParent;
            data.children = data.subs;
            arr.push(data);
            // arr.push({
            //     id:data.id,
            //     name:data.name,
            //     treeKey:`${topPrefix}0-${data.id}`,
            //     isParent:data.isParent,
            //     isLeaf:!data.isParent,
            //     isVirtual:data.isVirtual,
            //     type:data.type,
            //     companyid:data.companyid,
            //     children:data.subs,
            //     canClick:data.canClick,
            //     shadowInfo:data.shadowInfo,
            // });
        }
    }else{
        const loop = datas =>{
            for (let i=0;i<datas.length;i++) {
                const data = datas[i];
                const {treeKey,id} = treeNode.props;
                data.treeKey = `${treeKey}-${data.id}`;
                data.isLeaf = !data.isParent;
                arr.push(data);
                // arr.push({
                //     id:data.id,
                //     name: data.name,
                //     treeKey:`${treeKey}-${data.id}`,
                //     isParent:data.isParent,
                //     isLeaf:!data.isParent ,
                //     isVirtual:data.isVirtual,
                //     type:data.type,
                //     canClick:data.canClick,
                //     shadowInfo:data.shadowInfo,
                // });
            }
        }
        loop(datas[0].datas);
    }
    // console.log('arr',arr);
    return arr;
}

function getNewTreeData(treeData, curKey, child, level) {
    // console.log("treeData, curKey, child, level",treeData, curKey, child, level);
    const loop = data => {
        // if (level < 1 || curKey.length - 3 > level * 2) return;
        data.forEach((item) => {
            //console.log(curKey.indexOf(item.treeKey) === 0);
            if ((curKey+"-").indexOf(item.treeKey+"-") === 0) {
                // console.log("curKey",curKey,item.treeKey);
            //if (curKey.indexOf(item.treeKey) === 0) {
                if (item.children) {
                    loop(item.children);
                } else {
                    item.children = child;
                }
            }
        });
    };
    loop(treeData);
}
export default Main;